#include "../common/dispatch.hpp"
#include <thread>

void onRpcResponse(const rpc::BaseConnection::ptr conn, rpc::RpcResponse::ptr& msg)
{
    std::cout << "收到了Rpc响应" << std::endl;
    std::string body = msg->serialize();
    std::cout << body << std::endl;
}

void onTopicResponse(const rpc::BaseConnection::ptr conn, rpc::TopicResponse::ptr& msg)
{
    std::cout << "收到了Topic响应" << std::endl;
    std::string body = msg->serialize();
    std::cout << body << std::endl;
}

int main()
{
    auto dispatcher = std::make_shared<rpc::Dispatcher>();
    dispatcher->registerHandler<rpc::RpcResponse>(rpc::Mtype::RSP_RPC,onRpcResponse);
    dispatcher->registerHandler<rpc::TopicResponse>(rpc::Mtype::RSP_TOPIC,onTopicResponse);
    
    auto client = rpc::CilentFactory::create("127.0.0.1",9090);
    auto msg_cb = std::bind(&rpc::Dispatcher::onMessage,dispatcher.get(),std::placeholders::_1,std::placeholders::_2);
    client->setMessageCallback(msg_cb);
    
    client->connect();

    auto rpc_req = rpc::MessageFactory::create<rpc::RpcRequest>();
    rpc_req->setid("123");
    rpc_req->setMethod("Add");
    rpc_req->setmtype(rpc::Mtype::REQ_RPC);

    Json::Value val;
    val["num1"] = 11;
    val["num2"] = 22;
    rpc_req->setParams(val);
    client->send(rpc_req);
    
    auto topic_req = rpc::MessageFactory::create<rpc::TopicRequest>();
    topic_req->setid("234");
    topic_req->setmtype(rpc::Mtype::REQ_TOPIC);
    topic_req->setTopicKey("news");
    //主题发布才有消息字段
    topic_req->setOptype(rpc::TopicOptype::TOPIC_PUBLISH);
    topic_req->setTopicMsg("重大新闻");
    client->send(topic_req);
    
    std::this_thread::sleep_for(std::chrono::seconds(5));
    client->shutdown();
    return 0;   
}